import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/product_plateconsumption_odoo_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/models/odoo/product_plateconsumption.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';
import '../../../generated/l10n.dart';

class ProductPlateconsumptionEdit extends StatefulWidget {
  ProductPlateconsumptionEdit({this.productPlateconsumption});

  final ProductPlateconsumption? productPlateconsumption;

  @override
  _ProductPlateconsumptionEditState createState() => _ProductPlateconsumptionEditState();
}

class _ProductPlateconsumptionEditState extends State<ProductPlateconsumptionEdit> {
  late ProductPlateconsumption productPlateconsumption;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  //late List<SelectOptionVO> activeList;

  List<SelectOptionVO> productList = [];

  List<SelectOptionVO> thicknessList = [];

  List<SelectOptionVO> stationList = [];

  List<SelectOptionVO> filledList = [];

  late bool isLoading;

  late var _subscription;

  @override
  void initState() {
    super.initState();
    this.isAdd = widget.productPlateconsumption == null;
    this.isLoading = isDisplayDesktop(Cry.context)?false:true;
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "plateconsumptionEdit")
        .listen(_onEnvent);
    this.productPlateconsumption = widget.productPlateconsumption ?? ProductPlateconsumption();
    _loadSelectVO();
  }

  @override
  void dispose(){
    StoreUtil.write("key", "productPlateconsumption");
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码后的结果
  void _onEnvent(dynamic obj) async{
    ResponseBodyApi res = await DynamicDataApi.getModels(model: "res.users",key: 'login',val: obj["scan"]);
    if(res.success!){
      if(res.data.length == 0){
        CryUtils.message("该人员不存在");
        return ;
      }else if(res.data.length > 1){
        CryUtils.message("编号重复");
        return ;
      }else {
        if(isAdd!){
          var index = _getUserIndex(res.data[0]["id"].toString());
          if(index == -1){
            CryUtils.message("该人员不属于${StoreUtil.read(
                Constant.KEY_PRODUCTIONSTATION)["teamName"]}");
            return ;
          }
          isLoading = false;
          productPlateconsumption.filledUid = res.data[0]["id"]!=false?res.data[0]["id"].toString():"";
          productPlateconsumption.filledName = filledList[index].label.toString();
        }else{
          if(productPlateconsumption.filledUid != res.data[0]["id"].toString()){
            CryUtils.message("您没有修改权限");
            setState(() {});
            return ;
          }
          isLoading = false;
          productPlateconsumption.filledUid = res.data[0]["id"].toString();
        }
        setState(() {});
      }
    }
  }

  int _getUserIndex(String id) {
    for (var i = 0 ; i<filledList.length ; i++) {
      if(id == filledList[i].value){
        return i;
      }
    }
    return -1;
  }

  _loadSelectVO() async{
    productList = await DynamicDataApi.getModelSelect(
      model: "product.template", name: "name",
      key: "type",val: "consu",
      key2: 'categ_id.name',operator2: 'like',val2: '%钣金原材料%',
      order: OrderItemModel(column: 'sequence', asc: true)
    );

    if(isDisplayDesktop(Cry.context)){
      ResponseBodyApi res = await DynamicDataApi.getModels(
          model: "base.team",
          key: "teamcode",
          val: "BJSC"
      );
      if(res.success!){
        stationList = await DynamicDataApi.getModelSelect(
            model: "base.productionstation",
            name: "stationname",
            key: "team_id",
            val: res.data[0]["id"]
        );
        try{
          ResponseBodyApi filledUser = await DynamicDataApi.getModels(
              model: "base.teamuser",
              key: "team_id",
              val: res.data[0]["id"]
          );
          if (filledUser.success!) {
            for (int i = 0; i < filledUser.data.length; i++) {
              filledList.add(SelectOptionVO(
                  value: filledUser.data[i]["staff_id"][0].toString(),
                  label: filledUser.data[i]["staff_id"][1].toString())
              );
            }
          }else{
            filledList = [];
          }
        }catch(e){
          filledList = [];
        }
      }
    }else{
      var map = StoreUtil.read(Constant.KEY_PRODUCTIONSTATION);
      productPlateconsumption.stationId = map["stationId"].toString();
      productPlateconsumption.stationName = map["stationName"].toString();
      filledList = StoreUtil.read(Constant.KEY_REPORTWORKERLIST);
    }

    thicknessList = await DynamicDataApi.getDictList("platethickness");

    setState(() { });
  }

  _reset(){
    productPlateconsumption = ProductPlateconsumption(
      stationId: productPlateconsumption.stationId,
      stationName:  productPlateconsumption.stationName,
      filledUid: productPlateconsumption.filledUid,
      filledName: productPlateconsumption.filledName,
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            label: '板材名称',
            dataList: productList,
            value: productPlateconsumption.productId,
            onSaved: (v) {
              productPlateconsumption.productId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CrySelect(
            label: '厚度(mm)',
            value: productPlateconsumption.thicknessId,
            dataList: thicknessList,
            onSaved: (v) {
              productPlateconsumption.thicknessId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            label: '长度(mm)',
            value: productPlateconsumption.length,
            onSaved: (v) {
              productPlateconsumption.length = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            label: '宽度(mm)',
            value: productPlateconsumption.width,
            onSaved: (v) {
              productPlateconsumption.width = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          // CryInputNum(
          //   label: '重量(KG)',
          //   value: productPlateconsumption.weight,
          //   onSaved: (v) {
          //     productPlateconsumption.weight = v;
          //   },
          //   validator: (v) {
          //     return v!.isEmpty ? S.of(context).required : null;
          //   },
          // ),

          CryInputNum(
            label: '消耗张数(张)',
            value: productPlateconsumption.consumednumber,
            onSaved: (v) {
              productPlateconsumption.consumednumber = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          isDisplayDesktop(context)?CrySelect(
            label: '设备工位',
            value: productPlateconsumption.stationId,
            dataList: stationList,
            onSaved: (v) {
              productPlateconsumption.stationId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ):CryInput(
            label: '设备工位',
            value: productPlateconsumption.stationName,
            enable: false,
            onSaved: (v) {
              productPlateconsumption.stationName = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          isDisplayDesktop(context)?CrySelect(
            label: '填报人',
            value: productPlateconsumption.filledUid,
            dataList: filledList,
            onSaved: (v) {
              productPlateconsumption.filledUid = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ):CryInput(
            label: '填报人',
            value: productPlateconsumption.filledName,
            enable: false,
            onSaved: (v) {
              productPlateconsumption.filledName = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInput(
            label: '备注',
            value: productPlateconsumption.remark,
            onSaved: (v) {
              productPlateconsumption.remark = v;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            if(isBlank(productPlateconsumption.filledDate)){
              productPlateconsumption.filledDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
            }
            ProductPlateconsumptionOdooApi.saveOrUpdate(productPlateconsumption.toOdooMap()).then((ResponseBodyApi res) {
              if (!res.success!) {
               //package:flutter_admin/pages/common/cry(re s.message!);
                return;
              }
              CryUtils.message(S.of(context).saved);
              if(isAdd!){
                _reset();
                return ;
              }
              Navigator.pop(context, true);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            if(isAdd!){
              Navigator.pop(context,true);
              return ;
            }
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return SizedBox.shrink();
          },
        ),
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: Stack(
        alignment:Alignment.center ,
        fit: StackFit.expand, //未定位widget占满Stack整个空间
        children: <Widget>[
          SingleChildScrollView(
            child: form,
          ),
          isLoading?Positioned(
            // top: 18.0,
            child: Container(
              width: 650,
              height: 650,
              color: Colors.black87,
              child: Center(
                child: Text("请扫描人员",style: TextStyle(
                    fontSize: 36,
                    color: Colors.red
                ),),
              ),
            ),
          ):Container(),
        ],
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}